package se.hrbustrc.hlgshopping.interceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import se.hrbustrc.hlgshopping.service.UserService;
import se.hrbustrc.hlgshopping.utils.JwtUtils;
import se.hrbustrc.hlgshopping.utils.UserContext;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 认证拦截器，对于需要验证用户的接口进行拦截
 */
@Component
public class AuthInterceptor implements HandlerInterceptor {
    @Autowired
    private UserService userService;
    @Autowired
    private JwtUtils jwtUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取token
        String token = request.getHeader("Authorization");
        System.out.println("Intercepted request to: " + request.getRequestURI());
        System.out.println("Authorization header: " + token);

        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
            System.out.println("Extracted token: " + token);
            // 验证并解析token
            if (userService.validateToken(token)) {
                System.out.println("Token is valid");
                Long userId = jwtUtil.getUserIdFromToken(token);
                System.out.println("Extracted userId from token: " + userId);
                if (userId != null) {
                    UserContext.setUserId(userId);
                    System.out.println("Set userId in UserContext: " + userId);
                    return true;
                } else {
                    System.out.println("Failed to extract userId from token");
                }
            } else {
                System.out.println("Token validation failed");
            }
        } else {
            System.out.println("No valid Bearer token found");
        }

        response.setStatus(401);
        response.getWriter().write("{\"code\":401,\"message\":\"未授权访问\"}");
        return false;
    }
}